# -*- coding: utf-8 -*-
###############################################################################
# file    : views_project_admin.py
# author  : wangyubin
# date    : Fri Apr 18 16:07:12 2014
# 
# brief   : views for 管理 项目
# history : init
###############################################################################

# uliweb lib
from uliweb import expose, functions
# python lib
import os
import datetime
# CM-box lib
from db_app.model_define import *
from comm_app.my_log import App_Log
from comm_app import utils

@expose('/admin')
class views_project_admin(object):
    """ 工程管理
    """
    def __init__(self):
        pass


    @expose('index')
    def index(self):
        
        return {
            "projs": T_PROJECT.all(),
        }


    @expose('proj-edit/<int:p_id>')
    def edit(self, p_id):
        """ 新建或者编辑项目
        """

        if p_id == 0:           # 新建
            return {
                "title": u"新建项目",
                "proj_id": 0,
                "proj_name": "",
                "proj_desc": "",
                "proj_users": [],
            }
        else:                   # 修改
            proj = T_PROJECT.get(p_id)
            return {
                "title": u"编辑项目",
                "proj_id": proj.id,
                "proj_name": proj.name,
                "proj_desc": proj.desc,
                "proj_users": proj.users,
            }
            

    @expose('proj-save')
    def save(self):
        """ 保存项目
        """
        
        proj_id = int(request.POST.get("proj_id"))
        proj_name = request.POST.get("proj_name")
        proj_desc = request.POST.get("proj_desc")
        proj_userids = request.POST.getlist("proj_userids[]")

        App_Log.logger.debug(u'proj_id: ' + repr(proj_id))
        App_Log.logger.debug(u'proj_name: ' + proj_name)
        App_Log.logger.debug(u'proj_desc: ' + proj_desc)
        App_Log.logger.debug(u'proj_userids:' + repr(proj_userids))

        proj = T_PROJECT()
        if proj_id != 0:        # project编辑
            proj = T_PROJECT.get(proj_id)

        # project重名的判断
        if T_PROJECT.filter(T_PROJECT.c.name == proj_name)\
                    .filter(T_PROJECT.c.id != proj_id).count() > 0:
            return json({
                "result": "NG",
                "message": settings.MESSAGE.ADMIN_MSG_01 % proj_name,
            })

        proj.name = proj_name
        proj.desc = proj_desc
        proj.create_user = request.user
        proj.save()
        
        if proj.users:
            proj.users.clear()

        for user_id in proj_userids:
            user = T_USER.get(int(user_id))
            proj.users.add(user)

        proj.save()
        return json({
            "result": "OK",
            "message": ""
        })


    @expose('get-users')
    def get_users(self):
        """ 获取可以加入项目的用户
        """
        App_Log.logger.debug(request.POST)
        proj_userids = request.POST.getlist("proj_userids[]")
        App_Log.logger.debug(u'proj_userids: ' + repr(proj_userids))


        all_users = T_USER.filter(T_USER.c.name != 'admin')
        select_users = []
        for user in all_users:
            if proj_userids.count(str(user.id)) == 0:
                dic_user = {}
                dic_user["id"] = user.id
                dic_user["name"] = user.name
                dic_user["real_name"] = user.real_name
                dic_user["email"] = user.email
                select_users.append(dic_user)

        return json({
            "result": "OK",
            "message": "",
            "select_users": select_users,
        })
        

    @expose('del-proj')
    def delete(self):
        """ 删除项目
        """

        proj_id = request.POST.get("proj_id");
        App_Log.logger.debug(u'proj_id: ' + proj_id)

        proj = T_PROJECT.get(int(proj_id))
        # 项目相关用户关系
        if proj.users:
            proj.users.clear()

        # 项目相关bug
        if proj.bugs:
            proj.bugs.remove()

        # 删除项目
        proj.delete()
        
        return json({
            "result": "OK",
            "message": "",
        })
    
